﻿using Microsoft.Office.Interop.Word;
using System.Net.NetworkInformation;
using ValidationResult = System.ComponentModel.DataAnnotations.ValidationResult;

namespace WordCloudClient.Common
{
    public class CommonHelper
    {
        public static bool IsCanPing(string ip)
        {
            Ping pingSender = new();
            PingReply reply = pingSender.Send(ip, 120);//第一个参数为ip地址，第二个参数为ping的时间
            return reply.Status == IPStatus.Success;
        }
        /// <summary>
        /// 获取文件地址
        /// </summary>
        /// <param name="title">弹出窗口标题</param>
        /// <param name="filter">文件格式过滤</param>
        /// <returns></returns>
        public static string GetFileAddress(string title, string filter)
        {
            OpenFileDialog dialog = new()
            {
                Multiselect = false, //该值确定是否可以选择多个文件
                Title = title,
                Filter = filter + "所有文件(*.*)|*.*"
            };
            return dialog.ShowDialog() == true ? dialog.FileName : string.Empty;
        }
        /// <summary>
        /// 获取文件地址
        /// </summary>
        /// <param name="title">弹出窗口标题</param>
        /// <param name="filter">文件格式过滤</param>
        /// <param name="location">指定打开文件位置</param>
        /// <returns></returns>
        public static string GetFileAddress(string title, string filter,string location)
        {
            OpenFileDialog dialog = new()
            {
                Multiselect = false, //该值确定是否可以选择多个文件
                Title = title,
                Filter = filter + "所有文件(*.*)|*.*",
                InitialDirectory = location
            };
            return dialog.ShowDialog() == true ? dialog.FileName : string.Empty;
        }

        /// <summary>
        /// 获取指定位置所有文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string[] GetAllFolders(string path)
        {
            return Directory.GetDirectories(path);
        }
        /// <summary>
        /// 获取指定位置所有文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string[] GetAllFiles(string path)
        {
            return Directory.GetFiles(path);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteFile(string path)
        {
            if (Directory.Exists(path))
            {
                File.Delete(path);
            }

        }

        public static void OpenFileByExplorer(string address)
        {
            if (string.IsNullOrEmpty(address))
            {
                MessageTips.ErrorMessage("地址为空，请检查！");
                return;
            }
            Process.Start("explorer.exe", address);
        }


        /// <summary>
        /// 特性验证
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static bool AttributeVerify(object o)
        {
            ValidationContext context = new(o, null, null);
            List<ValidationResult> validationResults = new();
            bool valid = Validator.TryValidateObject(o, context, validationResults, true);
            if (!valid)
            {
                MessageTips.InfoMessage(validationResults[0].ErrorMessage!);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 时间戳反转为时间，有很多中翻转方法，但是，请不要使用过字符串（string）进行操作，大家都知道字符串会很慢！
        /// </summary>
        /// <param name="TimeStamp">时间戳</param>
        /// <param name="AccurateToMilliseconds">是否精确到毫秒</param>
        /// <returns>返回一个日期时间</returns>
        public static DateTime GetTime(long timestamp)
        {
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan timeSpan = new(lTime);
            DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
            return targetDt;
        }
        /// <summary>
        /// 将string转换为StreamReader
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static StreamReader StrConvertStreamReader(string str)
        {
            //convert string 2 stream            
            byte[] array = Encoding.ASCII.GetBytes(str);
            MemoryStream stream = new(array);             //convert stream 2 string      
            StreamReader reader = new(stream);
            return reader;
        }

        /// <summary>
        /// 读取word文档内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadWordDocument(string filePath)
        {
            // 创建 Word 应用程序对象
            Microsoft.Office.Interop.Word.Application wordApp = new();

            // 打开文档
            Document wordDoc = wordApp.Documents.Open(filePath);

            // 读取文本内容
            string content = wordDoc.Content.Text;

            // 关闭文档
            wordDoc.Close();

            // 退出 Word 应用程序
            wordApp.Quit();

            return content;
        }
        /// <summary>
        /// 相对路径转化为绝对路径
        /// </summary>
        /// <param name="relative"></param>
        /// <returns></returns>
        public static string UrlRelativeToAbsolute(string relative)
        {
            string absolutePath = Path.GetFullPath(relative);
            return absolutePath;
        }
    }
}
